package com.baiduapi.location$ip
{
	import com.baiduapi.Config;
	import com.baiduapi.events.BaiduLBS_LocationEvent;
	import com.baiduapi.location$ip.datas.BaiDuLBS_Location;
	import com.baiduapi.namespaces.Baidu_LBS;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	use namespace Baidu_LBS
	[Event(name="baidulbs_location_complete", type="com.baiduapi.events.BaiduLBS_LocationEvent")]
	
	/**
	 * 百度ip定位 
	 * @author Administrator
	 * 
	 */	
	
	public class BaiduLBS_LoaderLocation extends EventDispatcher
	{
		public static const VERSION:String="v1.1"
			
			
		private static const URL:String="http://api.map.baidu.com/location/ip"
			
		
		
		public function BaiduLBS_LoaderLocation()
		{
			super();			
		}
		
		/**
		 *  开始获取
		 * @param ip  可不填,不填时将默认 服务器获取访问者的ip
		 * @param ak  用户密钥,不填时将默认为Config静态属性ak,请先配置 
		 */		
		public function load(ip:String=null,ak:String=null):void{
			var loader:URLLoader=new URLLoader()
			
			loader.addEventListener(Event.COMPLETE,onComplete)
			loader.addEventListener(IOErrorEvent.IO_ERROR,onComplete)
				
				
			var req:URLRequest=new URLRequest();
			req.url=URL;
			var data:URLVariables=new URLVariables()
			data.ak=ak?ak:Config.ak
			data.coor="bd09ll"
			if(ip!=null)data.ip=ip
			req.data=data
			req.method=URLRequestMethod.GET
		
				
			loader.load(req)
		}
		private function onComplete(e:Event):void{
			var loader:URLLoader=e.target as URLLoader
			loader.removeEventListener(Event.COMPLETE,onComplete)
			loader.removeEventListener(IOErrorEvent.IO_ERROR,onComplete)
			var d:BaiDuLBS_Location
			if(e.type==Event.COMPLETE){
				var json:String=String(loader.data)
				try
				{
					d=new BaiDuLBS_Location(JSON.parse(json))
					
				} 
				catch(error:Error) 
				{
					d=new BaiDuLBS_Location()
				}
				
			}
			dispatchEvent(new BaiduLBS_LocationEvent(BaiduLBS_LocationEvent.COMPLETE,false,false,d))
			loader=null
		}
		
		
	}
}